<?php


namespace app\api\controller;

use app\admin\model\Admin;
use app\api\model\AccountType;
use app\api\model\SetAccount;
use app\api\model\SetAccountFlow as Model;
use app\api\model\StoreModel;
use app\api\validate\SetAccountTransferValidate;
use app\http\GetUid;
use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use think\facade\Request;
use app\api\service\SetAccountTransfer as Service;

/**
 * 结算账户流水
 * Class setAccountFlow
 * @package app\api\controller
 */
class SetAccountFlow extends Common
{
    /**
     * @param Request $request
     * @param Model $flow
     * @return \think\response\Json
     */
    public function store(Request $request, Model $flow, SetAccountTransferValidate $validate)
    {
        $data = $request::param();
        if (!$validate->scene($request::param('type'))->check($data)) {
            return $this->returnJson(422, $validate->getError());
        }
        $data['maker'] = GetUid::getUId();
        switch ($request::param('type', 0)) {
            case 'mutual':
                $res = Service::mutualTransfer($data);
                break;
            case 'in':
                $res = Service::inTransfer($data);
                break;
            case 'out':
                $res = Service::outTransfer($data);
                break;
            case 'adjustment':
                $res = Service::adjustment($data);
                break;
            default:
                $res = false;
        }
        if ($res) {
            return $this->returnJson(200, 'ok', $res);
        } else {
            return $this->returnJson(500, 'fail');
        }
    }

    /**
     * @param \think\facade\Request $request
     * @param Model $flow
     * @return \think\response\Json
     */
    public function index(Request $request)
    {
        $whereAccount = [];
        $whereFlow = [];
        //日期：
        if ($request::has('start_time', 'param', true) && $request::has('end_time', 'param', true)) {
            $whereFlow[] = ['create_time', 'between', [$request::param('start_time'), $request::param('end_time')]];
        }
        // 账目类型：
        if ($request::param('account_type')) {
            $whereFlow[] = ['account_type_id', '=', $request::param('set_account')];
        }
        // 结算账户：
        if ($request::param('set_account')) {
            $whereAccount[] = ['id', '=', $request::param('set_account')];
        }
        // 单号：
        if ($request::param('number')) {
            $whereFlow[] = ['business_number', 'LIKE', '%' . $request::param('number') . '%'];
        }
        // 操作人：
        if ($request::param('maker')) {
            $whereFlow[] = ['maker', '=', $request::param('maker')];
        }
        //账户所属门店：
        if ($request::param('account_store')) {
            $whereAccount[] = ['store', '=', $request::param('account_store')];
        }
        // 结算方式：
        if ($request::param('payment_mode')) {
            $whereFlow[] = ['payment_mode', '=', $request::param('payment_mode')];
        }
        // 备注：
        if ($request::param('des')) {
            $whereFlow[] = ['des', 'LIKE', '%' . $request::param('des') . '%'];
        }
        // 交易类型：
        if ($request::param('type', 0)) {
            $whereFlow[] = ['business_type', '=', $request::param('type', 0)];
        }
        $account = SetAccount::where($whereAccount)->fetchCollection()->column('id');
        $res = \app\api\model\SetAccountFlow::with(['setAccount'])
            ->where('customer_type', 'set_account')
            ->where($whereFlow)->where('set_account_id', 'IN', $account)
            ->page($request::param('page', 1), $request::param('size', 10))
            ->paginate($request::param('size', 10))
            ->each(function ($v) {
//                if($v->customer_type == 'set_account')
                $v->customer_name = SetAccount::find($v->customer_id)['name'];
                $v->maker_name = Admin::find($v['maker'])['name'];
                $v->account_type_name = AccountType::find($v['account_type_id'])['name'];
                $v->set_account_name = SetAccount::find($v['set_account_id'])['name'];
                // 盈余
                $v->surplus = $v->in_amount - $v->out_amount;
            });
        $info['in_amount'] = array_sum($res->getCollection()->column('in_amount'));
        $info['out_amount'] = array_sum($res->getCollection()->column('out_amount'));
        $info['surplus'] = array_sum($res->getCollection()->column('surplus'));
        return $this->returnJson(200, 'ok', array_merge($res->toArray(), $info));
    }

    public function indexSetAccount(Request $request)
    {
        $whereFlow = [];
        //日期：
        if ($request::has('start_time', 'param', true) && $request::has('end_time', 'param', true)) {
            $whereFlow[] = ['create_time', 'between', [$request::param('start_time'), $request::param('end_time')]];
        }
       
        $res = \app\api\model\SetAccount::with([
            'flows' => function($query) use($whereFlow){$query->where($whereFlow);},
            ])
            // ->where($whereFlow)
            ->page($request::param('page', 1), $request::param('size', 10))
            ->paginate($request::param('size', 10))
            ->each(function ($v) {
//                if($v->customer_type == 'set_account')
                // $v->customer_name = SetAccount::find($v->customer_id)['name'];
                // $v->maker_name = Admin::find($v['maker'])['name'];
                // $v->account_type_name = AccountType::find($v['account_type_id'])['name'];
                // $v->set_account_name = SetAccount::find($v['set_account_id'])['name'];
                // 盈余
                // dump(array_sum($v->flows->column('in_amount')));
                // dump(array_sum($v->flows->column('out_amount')));
                // echo PHP_EOL;
                // \dump(array_sum($v->flows->column('in_amount')) - array_sum($v->flows->column('out_amount')));
                // echo '--------------------------------------------------------';
                // echo PHP_EOL;
                // 支入 
                $v->in_amount = array_sum($v->flows->column('in_amount'));
                // 支出
                $v->out_amount = array_sum($v->flows->column('out_amount'));
                // 盈余
                $v->surplus = array_sum($v->flows->column('in_amount')) - array_sum($v->flows->column('out_amount'));
            })
            ;
        $info['in_amount'] = array_sum($res->getCollection()->column('in_amount'));
        $info['out_amount'] = array_sum($res->getCollection()->column('out_amount'));
        $info['surplus'] = $info['in_amount'] -$info['out_amount'];
        return $this->returnJson(200, 'ok', array_merge($res->toArray(), $info));
        // return $this->returnJson(200, 'ok', $res);

    }

    /**
     * @param $id
     * @param Model $flow
     * @return \think\response\Json
     */
    public function show($id, Model $flow)
    {
        try {
            return $this->returnJson(200, 'ok', $flow->findOrFail($id));
        } catch (DataNotFoundException $e) {
            return $this->returnJson(500, $e->getMessage());
        } catch (ModelNotFoundException $e) {
            return $this->returnJson(500, $e->getMessage());
        } catch (DbException $e) {
            return $this->returnJson(500, $e->getMessage());
        }
    }

    /**
     * @param \think\Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function collectionFlow(Request $request)
    {
        $where = [];
        // 操作人：
        if ($request::has('maker', 'param', true)) {
            $where[] = ['maker', '=', $request::param('maker')];
        }
        //单号：
        if ($request::has('number', 'param', true)) {
            $where[] = ['business_number', 'LIKE', '%' . $request::param('number') . '%'];
        }
        // 支付类型：
        if ($request::has('payment_mode', 'param', true)) {
            $where[] = ['payment_mode', '=', $request::param('payment_mode')];
        }
        //交易类型：
        if ($request::has('type', 'param', true)) {
            $where[] = ['business_type', '=', $request::param('type')];
        }
        // 操作人所属门店：
        if ($request::has('makerStore', 'param', true)) {
            $maker = Admin::where('store', $request::param('makerStore'))->fetchCollection()->select();
            $where[] = ['maker', 'IN', $maker->column('id')];
        }
        //日期：
        if ($request::has('start_time', 'param', true) && $request::has('end_time', 'param', true)) {
            $where[] = ['business_time', 'between', [
                strtotime($request::param('start_time')),
                strtotime($request::param('end_time'))
                ]
            ];
        }
        $res = \app\api\model\SetAccountFlow::where($where)
            ->page($request::param('page', 1), $request::param('size', 10))
            ->paginate($request::param('size', 10))->each(function ($v) {
                $v->store_name = StoreModel::find(Admin::find($v['maker'])['store'])['name'];
                $v->maker_name = Admin::find($v['maker'])['name'];
                $v->account_type_name = AccountType::find($v['account_type_id'])['name'];
                $v->set_account_name = SetAccount::find($v['set_account_id'])['name'];
            });
        return $this->returnJson(200, 'ok', $res);
    }
}
